<script setup>
import { Upload, Delete, View, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { draftApi } from '@/api/draft/index'
import { dateFormatter } from '@/utils/formatTime'
import videoPlayDialog from './videoPlayDialog.vue'

// 表单数据
const fusionForm = reactive({
  video1File: null,
  video2File: null,
  title: '',
  videoRemark: ''
})

// 融合按钮加载状态
const fusionLoading = ref(false)

const pagination = ref({
  total: 0,
  pageSize: 20,
  pageSizes: [10, 20, 30, 40],
  pageNo: 1
})

const videoDialogRef = ref()

const timer = ref(null)

// 融合任务列表
const fusionTaskList = ref([])

// 文件选择处理
const handleFileChange = (file, videoType) => {
  console.log(`${videoType} file:`, file)

  if (file.status === 'ready') {
    // 验证文件
    if (file.raw.size > 1024 * 1024 * 1024 * 2) {
      // 2GB 限制
      ElMessage.warning('文件大小不能超过2GB')
      return
    }

    // 直接存储文件
    fusionForm[`${videoType}File`] = file.raw
    ElMessage.success(`${videoType === 'video1' ? '第一个' : '第二个'}视频文件选择成功`)
  }
}

// 视频融合
const handleVideoFusion = () => {
  // 表单验证
  if (!fusionForm.video1File) {
    ElMessage.warning('请上传第一个视频文件')
    return
  }
  if (!fusionForm.video2File) {
    ElMessage.warning('请上传第二个视频文件')
    return
  }
  if (!fusionForm.title) {
    ElMessage.warning('请输入视频标题')
    return
  }
  if (!fusionForm.videoRemark) {
    ElMessage.warning('请输入视频描述')
    return
  }

  fusionLoading.value = true

  console.log('setVideoMerge', fusionForm)
  let params = new FormData()
  params.append('outputFormat', 'mp4')
  params.append('title', fusionForm.title)
  params.append('videoRemark', fusionForm.videoRemark)
  params.append('files', fusionForm.video1File)
  params.append('files', fusionForm.video2File)
  draftApi
    .setVideoMerge(params)
    .then((res) => {
      console.log('res', res)
      ElMessage.success('视频融合任务已提交，请在下方查看进度')
      getList()
    })
    .finally(() => {
      fusionLoading.value = false
      // 重置表单
      Object.assign(fusionForm, {
        video1File: null,
        video2File: null,
        title: '',
        videoRemark: ''
      })
    })
}

// 模拟融合进度
const simulateFusionProgress = (task) => {
  const timer = setInterval(() => {
    if (task.progress >= 100) {
      task.status = 'completed'
      clearInterval(timer)
      return
    }

    if (task.status === 'processing') {
      task.progress += Math.random() * 15
      if (task.progress > 100) task.progress = 100
    }
  }, 2000)
}

// 下载任务
const downLoadTask = (row) => {
  const a = document.createElement('a')
  a.href = row.url
  a.download = row.title // 同源时才生效；跨域时写空串即可
  document.body.appendChild(a) // Firefox 要求插入 DOM
  a.click()
  document.body.removeChild(a)
}

// 查看结果
const viewResult = (row) => {
  videoDialogRef.value.init(row.url)
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 2:
      return 'primary'
    case 3:
      return 'success'
    case 4:
      return 'danger'
    default:
      return 'primary'
  }
}

// 获取进度条颜色
const getProgressColor = (status) => {
  switch (status) {
    case 'processing':
      return '#6366f1'
    case 'completed':
      return '#22c55e'
    case 'failed':
      return '#ef4444'
    default:
      return '#94a3b8'
  }
}

function getList() {
  draftApi
    .getMaskList({
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.pageNo
    })
    .then((res) => {
      console.log('res', res)
      fusionTaskList.value = res.list
      pagination.value.total = res.total
    })
}

function getStatusText(text) {
  if (text <= 2) {
    return '任务正在处理中'
  } else if (text == 3) {
    return '任务已完成'
  } else if (text == 4) {
    return '任务处理失败'
  }
  return '-'
}

// 启动已有任务的进度模拟
onMounted(() => {
  getList()
  timer.value = setInterval(() => {
    getList()
  }, 30000)
})

onUnmounted(() => {
  clearInterval(timer.value)
})
</script>

<template>
  <div class="video-fusion-container">
    <!-- 视频融合表单 -->
    <el-card class="fusion-form-card">
      <div style="width: 100%; display: flex; justify-content: center">
        <el-form :model="fusionForm" label-width="120px" class="fusion-form">
          <!-- 上传视频1 -->
          <el-form-item label="上传视频1">
            <div class="upload-area">
              <el-upload
                class="video-upload"
                drag
                action="#"
                :auto-upload="false"
                :on-change="(file) => handleFileChange(file, 'video1')"
                :accept="'.mp4'"
                :show-file-list="false"
              >
                <div class="upload-content">
                  <el-icon class="upload-icon" size="48" color="#6366f1">
                    <Upload />
                  </el-icon>
                  <div class="upload-text">
                    <p class="upload-title">点击或拖拽第一个视频文件到此处</p>
                    <p class="upload-subtitle">支持MP4视频格式</p>
                  </div>
                </div>
              </el-upload>
              <!-- 显示已选择的文件名 -->
              <div v-if="fusionForm.video1File" class="file-info">
                <el-tag type="success">{{ fusionForm.video1File.name }}</el-tag>
              </div>
            </div>
          </el-form-item>

          <!-- 上传视频2 -->
          <el-form-item label="上传视频2">
            <div class="upload-area">
              <el-upload
                class="video-upload"
                drag
                action="#"
                :auto-upload="false"
                :on-change="(file) => handleFileChange(file, 'video2')"
                :accept="'.mp4'"
                :show-file-list="false"
              >
                <div class="upload-content">
                  <el-icon class="upload-icon" size="48" color="#6366f1">
                    <Upload />
                  </el-icon>
                  <div class="upload-text">
                    <p class="upload-title">点击或拖拽第二个视频文件到此处</p>
                    <p class="upload-subtitle">支持MP4视频格式</p>
                  </div>
                </div>
              </el-upload>
              <!-- 显示已选择的文件名 -->
              <div v-if="fusionForm.video2File" class="file-info">
                <el-tag type="success">{{ fusionForm.video2File.name }}</el-tag>
              </div>
            </div>
          </el-form-item>

          <!-- 视频标题 -->
          <el-form-item label="视频标题">
            <el-input v-model="fusionForm.title" placeholder="请输入融合后的视频标题" />
          </el-form-item>

          <!-- 视频描述 -->
          <el-form-item label="视频描述">
            <el-input
              v-model="fusionForm.videoRemark"
              type="textarea"
              :rows="4"
              placeholder="请输入视频描述，描述融合的效果和特色..."
            />
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              @click="handleVideoFusion"
              :loading="fusionLoading"
              size="large"
              style="width: 200px"
            >
              开始视频融合
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 融合任务列表 -->
    <el-card class="task-list-card">
      <div class="task-header">
        <h3>视频融合任务列表</h3>
      </div>
      <div style="width: 100%; display: flex; justify-content: center">
        <el-table :data="fusionTaskList" style="width: 100%" stripe>
          <el-table-column prop="title" label="任务标题" />
          <el-table-column prop="videoRemark" label="视频描述" />
          <el-table-column prop="publishStatus" label="状态" width="150" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.publishStatus)" size="small">
                {{ getStatusText(row.publishStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="160"
            :formatter="dateFormatter"
          />
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button
                  v-if="row.publishStatus == 3"
                  type="primary"
                  size="small"
                  @click="viewResult(row)"
                  circle
                >
                  <el-icon><View /></el-icon>
                </el-button>
                <el-button
                  v-if="row.publishStatus == 3"
                  type="danger"
                  size="small"
                  @click="downLoadTask(row)"
                  circle
                >
                  <el-icon><Download /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-row justify="end" style="margin-top: 10px">
        <el-pagination
          v-model:current-page="pagination.pageNo"
          v-model:page-size="pagination.pageSize"
          :page-sizes="pagination.pageSizes"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>
    <videoPlayDialog ref="videoDialogRef" />
  </div>
</template>

<style lang="scss" scoped>
.video-fusion-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20px;
}

/* 融合表单卡片 */
.fusion-form-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.fusion-form {
  width: 70%;
}

/* 文件上传区域 */
.upload-area {
  width: 100%;
}

.video-upload {
  width: 100%;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  text-align: center;
}

.upload-icon {
  margin-bottom: 16px;
}

.upload-text {
  color: #666;
}

.upload-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 8px 0;
  color: #1a1a1a;
}

.upload-subtitle {
  font-size: 14px;
  margin: 0;
  color: #999;
}

.file-info {
  margin-top: 10px;
  text-align: center;
}

/* 任务列表卡片 */
.task-list-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.task-header {
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.task-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

/* 进度条容器 */
.progress-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-text {
  font-size: 12px;
  color: #666;
  min-width: 35px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-buttons .el-button {
  padding: 6px;
  min-width: 32px;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 24px;
}

.el-select,
.el-input {
  width: 100%;
}

/* 上传组件样式 */
.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: auto;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.el-upload-dragger:hover {
  border-color: #6366f1;
  background-color: #f8f9ff;
}

/* 按钮样式 */
.el-button {
  border-radius: 6px;
  font-weight: 500;
}

.el-button--primary {
  background-color: #6366f1;
  border-color: #6366f1;
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
}

/* 进度条样式 */
.el-progress {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-fusion-container {
    padding: 10px;
  }

  .fusion-form {
    width: 95%;
  }

  .upload-content {
    padding: 20px 15px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .progress-container {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
